package com.deer.wms.ware.task.web;

import cn.hutool.core.util.ObjectUtil;
import com.deer.wms.intercept.annotation.User;
import com.deer.wms.intercept.common.data.CurrentUser;
import com.deer.wms.project.root.core.result.CommonCode;
import com.deer.wms.project.root.core.result.Result;
import com.deer.wms.project.root.core.result.ResultGenerator;
import com.deer.wms.project.root.exception.ServiceException;
import com.deer.wms.project.root.util.DateUtils;
import com.deer.wms.system.manage.model.user.UserInfo;
import com.deer.wms.system.manage.service.UserInfoService;
import com.deer.wms.ware.task.constant.WareTaskConstant;
import com.deer.wms.ware.task.model.SO.Merge;
import com.deer.wms.ware.task.model.SO.SoMasterCriteria;
import com.deer.wms.ware.task.model.SO.SoMasterDto;
import com.deer.wms.ware.task.model.Wave.*;
import com.deer.wms.ware.task.service.SoMasterService;
import com.deer.wms.ware.task.service.WaveDetailService;
import com.deer.wms.ware.task.service.WaveMasterService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.text.ParseException;
import java.util.List;

/**
 * Created by ll on 2020/02/02.
 */
@RestController
@RequestMapping("/wave/masters")
public class WaveMasterController {

    @Autowired
    private WaveMasterService waveMasterService;
    @Autowired
    WaveDetailService waveDetailService;
    @Autowired
    SoMasterService soMasterService;

    @PostMapping
    public Result add(@RequestBody WaveMaster waveMaster) {
        waveMasterService.save(waveMaster);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/delete")
    public Result delete(Integer id) {
        waveDetailService.deleteByWaveMasterId(id);
        waveMasterService.removeById(id);
        return ResultGenerator.genSuccessResult();
    }

    @Autowired
    private UserInfoService userInfoService;
    @PostMapping("/update")
    public Result update(@RequestBody WaveMaster waveMaster) {
        UserInfo userInfo  =userInfoService.getById(waveMaster.getAllotUserId());
        waveMaster.setAllotUserName(userInfo.getUserName());
        waveMaster.setAllotTime(DateUtils.getNowDateTimeString());
        waveMasterService.updateById(waveMaster);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/{id}")
    public Result detail(@PathVariable Integer id) {
        WaveMaster waveMaster = waveMasterService.getById(id);
        return ResultGenerator.genSuccessResult(waveMaster);
    }

    @GetMapping("/list")
    public Result list(WaveMasterCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<WaveMasterDto> list = waveMasterService.findList(criteria);
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @GetMapping("/allotWave")
    public Result allotWave(WaveMasterCriteria criteria, @ApiIgnore @User CurrentUser currentUser) {
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        criteria.setUserId(currentUser.getUserId());
        List<WaveMasterDto> list = waveMasterService.allotWave(criteria);
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @GetMapping("/generateWaves")
    public Result generateWaves() {
        waveMasterService.generateWaves();
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/transToWave")
    public Result transToWave(@RequestBody WaveDetailTransData waveDetailTransData) {
        WaveMaster wave = waveMasterService.getById(waveDetailTransData.getWaveId());
        for (Integer waveDetailId : waveDetailTransData.getWaveDetailIds()) {
            WaveDetail waveDetail = waveDetailService.getById(waveDetailId);
            waveDetail.setWaveMasterId(wave.getWaveId());
            waveDetailService.updateById(waveDetail);
        }
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/allotPickUser")
    public Result allotPickUser(Integer waveMasterId,Integer userId,String userName) {
        WaveMaster wave = waveMasterService.getById(waveMasterId);
        wave.setAllotTime(DateUtils.getNowDateTimeString());
        wave.setAllotUserId(userId);
        wave.setAllotUserName(userName);
        waveMasterService.updateById(wave);
        return ResultGenerator.genSuccessResult();
    }

//    @GetMapping("/listForPda")
//    public Result listForPda() {
//        List<WaveMasterDto> list = new ArrayList<>();
//        WaveMasterCriteria criteria = new WaveMasterCriteria();
//        criteria.setState(WareTaskConstant.WAVE_STATE_PICKING);
//        list.addAll(waveMasterService.findList(criteria));
//        criteria.setState();
//        PageInfo pageInfo = new PageInfo(list);
//        return ResultGenerator.genSuccessResult(pageInfo);
//    }


    @ApiOperation(value = "合并SO", notes = "生成波次（配料单）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    @PostMapping("/merge")
    public Result merge(@RequestBody Merge merge, @ApiIgnore @User CurrentUser currentUser) {
        SoMasterCriteria criteria = new SoMasterCriteria();
        criteria.setBillNos(merge.getBillNos());
        List<SoMasterDto> soMasters = soMasterService.findList(criteria);
        //校验SO的状态，只允许初始化的单据能生成波次
        for (SoMasterDto soMaster : soMasters) {
            if (ObjectUtil.notEqual(soMaster.getState(), WareTaskConstant.SO_STATE_INIT)) {
                throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "只允许新建状态的出库任务进行合并，请确认单据【"+soMaster.getBillNo()+"】");
            }
        }
        waveMasterService.mergeSo(soMasters, currentUser);
        return ResultGenerator.genSuccessResult();
    }
}